package com.ant.myagile

import java.text.SimpleDateFormat
class TeamService {

	ProjectService projectService

	def List<Team> getTeamByOwner(ownerId){
		def owner = Member.get(ownerId)
		def teams = Team.findAllByOwner(owner)
		if(teams.size() != 0)
			return teams
		return null
	}
	def List<Team> getTeamByMember(memberId){
		List<Team> teams = new ArrayList<Team>()
		def member = Member.get(memberId)
		def teamMembers = Team_Member.findAllByMember(member)
		if(teamMembers.size() != 0){
			for(i in teamMembers){
				if(i.member.id == memberId){
					teams.add(i.team)
				}
			}
			return teams
		}
		return null
	}
	def List<Team> getAllTeamByUser(memberId){
		List<Team> teams = new ArrayList<Team>()
		List<Team> teams1 = getTeamByOwner(memberId)
		List<Team> teams2 = getTeamByMember(memberId)
		for(i in teams1){
			teams.add(i)
		}
		for(i in teams2){
			teams.add(i)
		}
		return teams
	}
	def add_Team(){
	}
	def Project[] list_Project(){
		Project[] projects = Project.list()
		return projects
	}
	def List<Project> projectsOfMember(ownerId){
		def cr = Project.createCriteria()
		def projList = cr.list {
			createAlias ("owner", "owner")
			eq("owner.id", ownerId)
		}
		if(projList.size() != 0)
			return projList
		return null
	}
	def List<Project>  assignedProjList(Team t){

		List<Project>projectList = new ArrayList<Project>()
		List<Team_Project> tp1 = new ArrayList<Team_Project>()
		List<Team_Project> tp = Team_Project.list()
		if(tp.size() !=0){
			for(i in tp){
				def t1 = i.team
				if(t1.id == t.id){
					tp1.add(i)
				}
			}
			if(tp1.size() !=0){
				for(i in tp1){
					projectList.add(i.project)
				}
				return projectList
			}else{
				projectList = null
			}
		}
		return null;
	}
	def projInProgress(Team team){
		List<Project> projectList = assignedProjList(team)
		def projInProgress = new ArrayList<Project>()
		Iterator<Project> iter = projectList.iterator()
		while(iter.hasNext()){
			Project p = iter.next();
			Team_Project tmp = Team_Project.findByTeamAndProject(team,p)
			if(tmp.endDate == null){
				projInProgress.add(p)
			}
		}
		return projInProgress
	}
	def  List<Long> assignedProjIdList(Team team){
		List<Project> projectList = assignedProjList(team)

		def assignedProjIdList = new ArrayList<Long>()
		if(projectList != null){
			for(i in projectList){
				assignedProjIdList.add(i.id)
			}
			return assignedProjIdList
		}
		return null
	}
	def save_Team(teamName, mailGroup, description, establishedDate, projects, owner){
		Team team = new Team(teamName: teamName, mailGroup: mailGroup, description: description, establishedDate: establishedDate, owner: owner)
		team.save(failOnError : true)
		for(i in projects){
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String strDate = dateFormat.format(new Date())
			Date dateNow = dateFormat.parse(strDate)
			def teamProject = new Team_Project(startDate: dateNow, endDate: "")
			def project = Project.get(i)
			team.addToTeamProjects(teamProject)
			project.addToTeamProjects(teamProject)
			teamProject.save(failOnError : true)
		}
		return team
	}

	def getTeamById( id){
		Team t = Team.get(id)
		return t
	}
	def editTeam(id){
		Team t = Team.get(id)
		return t
	}

	def updateTeam(newTeamName, newMailGroup, newDescription, newEstablishedDate, id, newProjects, existProjects, deletedProjects){

		def oldTeam = Team.get(id)
		oldTeam.setTeamName(newTeamName)
		oldTeam.setMailGroup(newMailGroup)
		oldTeam.setDescription(newDescription)
		oldTeam.setEstablishedDate(newEstablishedDate)
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String strDate = dateFormat.format(new Date())
		Date dateNow = dateFormat.parse(strDate)
		def newTeam = oldTeam
		for(i in existProjects){
			Team_Project teamp = Team_Project.findByTeamAndProject(newTeam, Project.get(i))
			teamp.setEndDate(null);
			teamp.setStartDate(dateNow)
			teamp.save(failOnError : true)
		}
		for(i in deletedProjects){
			Team_Project teamp = Team_Project.findByTeamAndProject(newTeam, Project.get(i))
			teamp.setEndDate(dateNow)
			teamp.save(failOnError : true)
		}
		for(i in newProjects){

			def project = Project.get(i);
			def teamProject = new Team_Project(startDate: dateNow, endDate: "")
			newTeam.addToTeamProjects(teamProject)
			project.addToTeamProjects(teamProject)
			teamProject.save(failOnError : true)
		}
		return newTeam
	}
	def deleteTeamProj(Team_Project  tp){

		tp.delete(flush: true);
	}

	def checkIdInList( projIdList,  selectedProjId){
		def flag=false;
		for(i in projIdList){
			if(selectedProjId.toString()==i.toString()){
				flag=true
			}
		}
		return flag
	}

	def deleteTeam(Team t){
		List<Tracking> trackingList = Tracking.list()
		List<Long> idTeamInTracking = new ArrayList<Long>()
		for(i in trackingList){
			idTeamInTracking.add(i.team.id)
		}
		for(i in trackingList){
			if(i.team.id.toString() == t.id.toString()){
				i.delete(flush: true)
				t.delete(flush: true)
			}
		}
	}

	def deleteTeamProject(Team_Project tp){
		tp.delete(flush: true)
	}
	def delTeam(teamId){
		Team t = Team.findById(teamId)
		t.delete()
		return true
	}
	def removeProjectFromTeamProject(tId, pId){
		def c = Team_Project.count
		Long tidl = Long.parseLong(tId)
		Long pidl = Long.parseLong(pId)
		Team team = Team.get(tidl);
		team.discard()
		Project project = Project.get(pidl);
		Team_Project teamp = Team_Project.findByTeamAndProject(team, project)
		teamp.delete()
		return (c > Team_Project.count)
	}
	def searchTeam(query){
		def c = Team.createCriteria()
		List<Team> teams = c.list(){
			if(query){
				ilike("teamName", "%${query}%")
			}
		}
		return teams
	}
	def searchTeamByMail(query){
		def c = Team.createCriteria()
		List<Team> teams = c.list(){
			if(query){
				ilike("mailGroup", "%${query}%")
			}
		}
		return teams
	}

	def getMembersByTeamId(id){
		def results = Member.findAll("from Member a, Team b , Team_Member c where b.id = "+id+" and a.id = c.member and b.id = c.team and c.isAccepted=true")
		return results
	}

	def findTeamByProject(pid) {
		Project project = Project.get(pid);
		def teams = project.teamProjects.team
		if(teams) {
			return teams
		} else {
			return false
		}
	}

	/**
	 * Change memberId in teamId to position
	 * @param teamId
	 * @param memberId
	 * @param position
	 * @return
	 */
	def changePosition(teamId, memberId, position){
		def member = Member.get(memberId)
		def team = Team.get(teamId)
		def teamMember = Team_Member.findByMemberAndTeam(member, team)
		teamMember.position = position
	}

	/**
	 * 
	 * @param teamId
	 * @param memberId
	 * @return
	 */
	boolean removeMemberFromTeam(teamId, memberId){
		def member = Member.get(memberId)
		def team = Team.get(teamId)
		if (member == null || team == null) return false
		Team_Member teamMember = Team_Member.findByMemberAndTeam(member, team)
		if (teamMember != null){
			teamMember.delete(flush: true)
			return true
		}
		return false;
	}
}
